package com.javaee.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaee.entity.User;
import com.javaee.util.CryptographyUtil;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/Loginview")
	public String goLogin(){
		
		return "login";
	}
	
	@RequestMapping(value = "login")
	public String login(User user,HttpServletRequest request) {
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), CryptographyUtil.md5(user.getPassword(), "javaee"));
		try{
			subject.login(token); // 登录验证
//			return "success";
			return "redirect:/shiro/main.jsp";
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("user", user);
			request.setAttribute("errorInfo", "用户名或密码错误！");
			return "redirect:/login.jsp";
//			return "err";
		}
		
	}
	
	
	/**
	 * 注销
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public String  logout()throws Exception{
		SecurityUtils.getSubject().logout();
		return "redirect:/login.jsp";
	}
	
	@RequestMapping("/main")
	public String main(){
		
		return "shiro/main";
	}
}
